package com.rlz.framemm.util

import android.content.Context
import com.bumptech.glide.Glide
import com.bumptech.glide.GlideBuilder
import com.bumptech.glide.Registry
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool
import com.bumptech.glide.load.engine.cache.DiskLruCacheWrapper
import com.bumptech.glide.load.engine.cache.LruResourceCache
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.module.AppGlideModule
import com.rlz.image.GlideAppliesOptions
import com.rlz.image.config.OkHttpUrlLoader
import com.rlz.image.imageloader.BaseImageLoaderStrategy
import com.rlz.image.imageloader.ImageLoader
import com.rlz.net.NetManager
import okhttp3.Cache
import okhttp3.OkHttpClient
import java.io.File
import java.io.InputStream
import java.util.concurrent.TimeUnit

/**
 * Created by RLZ
 * on 2021/6/16
 *
 */

@GlideModule(glideName = "GlideRepid")
class GlideConfiguration : AppGlideModule() {

    companion object {
        const val IMAGE_DISK_CACHE_MAX_SIZE: Long = 100 * 1024 * 1024 //图片缓存文件最大值为100Mb

    }

    override fun applyOptions(context: Context, builder: GlideBuilder) {
        builder.setDiskCache {
            DiskLruCacheWrapper.create(createCachePath("Glide"), IMAGE_DISK_CACHE_MAX_SIZE)
        }
        val calculator = MemorySizeCalculator.Builder(context).build()
        val defaultMemoryCacheSize = calculator.memoryCacheSize
        val defaultBitmapPoolSize = calculator.bitmapPoolSize
        val customMemoryCacheSize = (1.2 * defaultMemoryCacheSize).toInt()
        val customBitmapPoolSize = (1.2 * defaultBitmapPoolSize).toInt()
        builder.setMemoryCache(LruResourceCache(customMemoryCacheSize.toLong()))
        builder.setBitmapPool(LruBitmapPool(customBitmapPoolSize.toLong()))

        val loadImgStrategy: BaseImageLoaderStrategy<*> = ImageLoader.get().loadImgStrategy!!
        if (loadImgStrategy is GlideAppliesOptions) {
            (loadImgStrategy as GlideAppliesOptions).applyGlideOptions(context, builder)
        }
    }

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        //Glide 默认使用 HttpURLConnection 做网络请求,在这切换成 OkHttp 请求
        registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(createOkHttp(context)))
    }

    override fun isManifestParsingEnabled(): Boolean {
        return false
    }

    private fun createCachePath(dirName: String): File {
        val file = File(dirName)
        if (!file.exists()) {
            file.mkdirs()
        }
        return file
    }

    private fun createOkHttp(context: Context): OkHttpClient {
        val cache = Cache(createCachePath("cache"), IMAGE_DISK_CACHE_MAX_SIZE)
        return OkHttpClient.Builder()
                .cache(cache)
                .readTimeout(NetManager.READ_TIMEOUT.toLong(), TimeUnit.SECONDS)
                .connectTimeout(NetManager.CONNECTION_TIMEOUT.toLong(), TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build()
    }
}